package demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Future<Integer> future = executorService.submit(new SumTask(1, 100));
        try {
            int sum = future.get();
            System.out.println("1到100的累加和为：" + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }

    static class SumTask implements java.util.concurrent.Callable<Integer> {
        private int start;
        private int end;

        public SumTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public Integer call() throws Exception {
            if (start == end) {
                return start;
            }
            int mid = (start + end) / 2;
            SumTask leftTask = new SumTask(start, mid);
            SumTask rightTask = new SumTask(mid + 1, end);
            ExecutorService executorService = Executors.newFixedThreadPool(2);
            Future<Integer> leftFuture = executorService.submit(leftTask);
            Future<Integer> rightFuture = executorService.submit(rightTask);
            int leftSum = leftFuture.get();
            int rightSum = rightFuture.get();
            executorService.shutdown();
            return leftSum + rightSum;
        }
    }
}

